import {
  Controller,
  HttpException,
  HttpStatus,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Public } from '../auth/auth.decorator';
import { WechatCheckService } from './wechat-check.service';
import { TextDTO } from './dto/text.dto';
import { MediaDTO } from './dto/media.dto';
import { UpdateWechatCheckDto } from './dto/update-wechat-check.dto';
import { AxiosResponse } from 'axios';
import { Response } from '../../infra/schema/response';
import { map } from 'rxjs/operators';
import { firstValueFrom } from 'rxjs';
import { HttpService } from '@nestjs/axios';

@ApiTags('小程序内容检测')
@Controller('wechatCheck')
export class WechatCheckController {
  constructor(
    private readonly wechatCheckService: WechatCheckService,
    private readonly httpService: HttpService,
  ) {}

  @Public()
  @Post('/text')
  @ApiOperation({ summary: '文本检测' })
  @ApiResponse({ type: Response<string> })
  async checkTextSafety(@Body() textDTO: TextDTO) {
    const { text } = textDTO;
    if (!text) {
      throw new HttpException('Text is required', HttpStatus.BAD_REQUEST);
    }
    const accessToken = await this.getAccessToken(); // 获取 access_token
    const url = `https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${accessToken}`;
    const data = {
      content: text,
    };
    const isSafe = await this.checkContent(url, data);
    return { isSafe };
  }
  @Public()
  @Post('/media')
  @ApiOperation({ summary: '音视频检测' })
  @ApiResponse({ type: Response<string> })
  async checkMideaSafety(@Body() medioDTO: MediaDTO) {
    const { media } = medioDTO;
    if (!media) {
      throw new HttpException('media is required', HttpStatus.BAD_REQUEST);
    }
    const accessToken = await this.getAccessToken(); // 获取 access_token
    const url = `https://api.weixin.qq.com/wxa/media_check_async?access_token=${accessToken}`;
    const data = {
      media_url: media,
      media_type: 2, // 1:音频;2:图片
    };
    const isSafe = await this.checkContent(url, data);
    return { isSafe };
  }
  async checkContent(url: any, data: Object): Promise<boolean> {
    try {
      const response = await firstValueFrom(
        this.httpService.post(url, data).pipe(map((res) => res.data)),
      );
      return response.errcode === 0; // 如果 errcode 为 0，则表示内容安全
    } catch (error) {
      console.error('Error occurred while checking text safety:', error);
      throw error;
    }
  }
  private async getAccessToken(): Promise<string> {
    //调用微信的获取 access_token
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${process.env.appid}&secret=${process.env.secret}`;

    try {
      const response = await firstValueFrom(
        this.httpService.get(url).pipe(map((res) => res.data)),
      );

      return response.access_token;
    } catch (error) {
      console.error('Error occurred while getting access token:', error);
      throw error;
    }
  }
}
